package com.zbkj.dal.common.validation;

import com.zbkj.dal.annotation.EnumValue;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ClockProvider;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

public class EnumValidator implements ConstraintValidator<EnumValue, String> {

    private Class<? extends Enum<?>> enumType;
    private Boolean allowNull;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        this.enumType = constraintAnnotation.value();
        this.allowNull = constraintAnnotation.allowNull();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        // 如果允许为空且值为空，则直接通过校验
        if (allowNull && value == null) {
            return true;
        }
        // 校验枚举值
        if (value != null) {
            for (Enum<?> e : enumType.getEnumConstants()) {
                if (StringUtils.equals(e.name(), value)) {
                    return true;
                }
            }
        }
        return false;
    }
}